package com.mlz.service.impl;


import com.mlz.mapper.DeptMapper;
import com.mlz.mapper.EmpMapper;
import com.mlz.pojo.Dept;
import com.mlz.pojo.DeptLog;
import com.mlz.service.DeptLogService;
import com.mlz.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;


    @Override
    public List<Dept> list() {
        List<Dept> deptList = deptMapper.list();
        return deptList;
    }



    @Transactional(rollbackFor = Exception.class)//当前方法添加了事务管理
    //根据部门id 删除部门信息以及部门下所有的员工
    @Override
    public void delete(Integer id) throws Exception {
        try {
            //1.根据部门id删除部门信息
            deptMapper.deleteById(id);
            //模拟异常发生
            //int i = 1/0;
            if (true){
                throw new Exception("编译时异常~~");
            }
            //2.删除部门下所有的员工信息
            empMapper.deleteByDeptId(id);
        } finally {
            //无论是否有异常，最终都要执行的代码：记录日志
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了删除部门的操作,当前删除部门是"+id+"部门");
            //调用其他业务类中的方法
           deptLogService.insert(deptLog);
        }

    }

    @Override
    public void add(Dept dept) {
        //补全部门全部数据
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        //调用持久层的添加功能
        deptMapper.insert(dept);
    }


}
